package threadLocal;

import java.util.concurrent.TimeUnit;

/**
 * @author: 李德才
 * @description:
 * @create: 2020-12-13 15:12
 **/
public class ThreadLocal2 {

    static ThreadLocal<Person> tl = new ThreadLocal<>();

    public static void main(String[] args) {

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("一个方法中的两个线程，获取不到：" + tl.get());
        }).start();

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            /**
             *  // 设置到了当前线程的 map 中
             *     public void set(T value) {
             *         Thread t = Thread.currentThread();
             *         ThreadLocalMap map = getMap(t);
             *         if (map != null) {
             *             map.set(this, value);
             *         } else {
             *             createMap(t, value);
             *         }
             *     }
             */
            tl.set(new Person());
            getPerson();
        }).start();
    }


    public static void getPerson() {
        System.err.println("同一线程中的不同方法可以获取到：" + tl.get().name);
    }

    static class Person {
        String name = "zhangsan";
    }

}
